<template>
  <div class="container">
    <div class="app-container">
      <!-- 内容 -->
      <el-card>
        <div slot="header" class="clearfix">
          <span>{{ $route.query.id ? "试题修改" : "试题录入" }}</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="form">
            <!-- 学科 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="学科："
                  prop="subjectID"
                >
                  <el-select
                    v-model="form.subjectID"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="subjectChange"
                  >
                    <el-option
                      v-for="(item, index) in subjects"
                      :key="index"
                      :label="item.subjectName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 目录 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="目录："
                  prop="catalogID"
                >
                  <el-select
                    style="width: 100%"
                    placeholder="请选择"
                    v-model="form.catalogID"
                  >
                    <el-option
                      v-for="(item, index) in directoryList"
                      :key="index"
                      :label="item.directoryName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 企业 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="企业："
                  prop="enterpriseID"
                >
                  <el-select
                    placeholder="请选择活动区域"
                    style="width: 100%"
                    v-model="form.enterpriseID"
                  >
                    <el-option
                      v-for="(item, index) in companyList"
                      :key="index"
                      :label="item.company"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 城市 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  class="city-box"
                  label-width="120px"
                  prop="province"
                  label="城市："
                >
                  <el-select
                    class="city-1"
                    placeholder="请选择"
                    v-model="form.province"
                    @change="onProvinceChange"
                  >
                    <el-option
                      v-for="(item, index) in province"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    class="city-2"
                    placeholder="请选择"
                    v-model="form.city"
                  >
                    <el-option
                      v-for="(name, i) in city"
                      :key="i"
                      :label="name"
                      :value="name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 方向 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="方向："
                  prop="direction"
                >
                  <el-select
                    style="width: 100%"
                    placeholder="请选择活动区域"
                    v-model="form.direction"
                  >
                    <el-option
                      v-for="(item, index) in direction"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 题型 -->
            <el-row>
              <el-col>
                <el-form-item
                  label-width="120px"
                  label="题型："
                  prop="questionType"
                >
                  <el-radio-group v-model="form.questionType">
                    <el-radio label="1">单选</el-radio>
                    <el-radio label="2">多选</el-radio>
                    <el-radio label="3">简答</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 难度 -->
            <el-row>
              <el-col>
                <el-form-item
                  label-width="120px"
                  label="难度："
                  prop="difficulty"
                >
                  <el-radio-group v-model="form.difficulty">
                    <el-radio label="1">简单</el-radio>
                    <el-radio label="2">一般</el-radio>
                    <el-radio label="3">困难</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 题干 -->
            <el-row>
              <el-col>
                <el-form-item
                  label-width="120px"
                  label="题干："
                  prop="question"
                >
                  <quill-editor
                    class="quill-editor"
                    ref="myTextEditor"
                    style="height: 200px ,width:auto"
                    v-model="form.question"
                  ></quill-editor>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 单选 -->
            <template v-if="form.questionType === '1'">
              <div v-for="(item, index) in array" :key="index">
                <el-row v-if="index < 4">
                  <el-col>
                    <el-form-item label-width="120px" label="选项：">
                      <el-row>
                        <el-col :span="1">
                          <el-radio :label="index" v-model="radio">{{
                            item.code
                          }}</el-radio>
                        </el-col>
                        <el-col :span="5">
                          <el-input v-model="item.title"></el-input>
                        </el-col>
                        <el-col :span="10">
                          <el-upload
                            class="upload-demo"
                            action="#"
                            multiple
                            :limit="3"
                          >
                            <el-button class="upload_btn">点击上传</el-button>
                          </el-upload>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <el-row>
                <el-col>
                  <el-button type="danger" class="addBtn" @click="addItem" disabled
                    >+增加选项与答案</el-button
                  >
                </el-col>
              </el-row>
            </template>
            <!-- 多选 -->
            <template v-if="form.questionType === '2'">
              <div v-for="(item, index) in array" :key="index">
                <el-checkbox-group v-model="checkedList">
                  <el-row v-if="index < questionIndex">
                    <el-col>
                      <el-form-item label-width="120px" label="选项：">
                        <el-row>
                          <el-col :span="1">
                            <el-checkbox :label="index">{{
                              item.code
                            }}</el-checkbox>
                          </el-col>
                          <el-col :span="5">
                            <el-input v-model="item.title"></el-input>
                          </el-col>
                          <el-col :span="10">
                            <el-upload
                              class="upload-demo"
                              action="#"
                              multiple
                              :limit="3"
                            >
                              <el-button class="upload_btn">点击上传</el-button>
                            </el-upload>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              <el-row>
                <el-col>
                  <el-button
                    class="addBtn"
                    type="danger"
                    size="small"
                    @click="addItem"
                    >+增加选项与答案</el-button
                  >
                </el-col>
              </el-row>
            </template>
            <!-- 解析视频 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="解析视频："
                  prop="videoURL"
                >
                  <el-input v-model="form.videoURL"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 解析 -->
            <el-row>
              <el-col>
                <el-form-item
                  label-width="120px"
                  prop="answer"
                  label="答案解析"
                >
                  <quill-editor
                    class="quill-editor"
                    ref="myTextEditor"
                    style="height: 200px ,width:auto"
                    v-model="form.answer"
                  ></quill-editor>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 题目备注 -->
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label-width="120px"
                  label="题目备注："
                  prop="remarks"
                >
                  <el-input
                    type="textarea"
                    :rows="2"
                    resize="none"
                    placeholder="请输入内容"
                    v-model="form.remarks"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 标签 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label-width="120px" label="题目标签：">
                  <el-select
                    multiple
                    allow-create
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="form.tags"
                  >
                    <el-option
                      v-for="item in tagList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 提交按钮 -->
            <el-form-item label-width="120px" label="">
              <el-button
                :type="$route.query.id ? 'success ' : 'primary'"
                @click="onClick($event)"
                >{{ $route.query.id ? "确认修改" : "确认提交" }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 学科接口
import { list as subList } from '@/api/hmmm/subjects'
// 目录接口
import { list as dirList } from '@/api/hmmm/directorys'
// 企业接口
import { list as company } from '@/api/hmmm/companys'
// 调取城市
import { provinces, citys as getCitys } from '@/api/hmmm/citys'
// 获取标签
import { simple as tagArr } from '@/api/hmmm/tags'
// 获取题库
import {
  add,
  detail as queList,
  update as queUpdate
} from '@/api/hmmm/questions'
export default {
  components: { quillEditor },
  data () {
    return {
      radio: '',
      checkedList: [], // 复选框列表
      subjects: [], // 学科列表
      directoryList: [], // 目录列表
      companyList: [], // 企业列表
      province: provinces(), // 城市
      city: [],
      tagList: [], // 标签列表
      direction: [
        'o2o',
        '外包服务',
        '企业服务',
        '互联网金融',
        '企业咨询',
        '互联网',
        '电子商务',
        '其他'
      ], // 方向
      difficulty: {
        1: '简单',
        2: '一般',
        3: '困难'
      },
      questionType: {
        1: '单选',
        2: '多选',
        3: '简答'
      },

      array: [
        {
          code: 'A', // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 正确答案
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'E',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'F',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'G',
          title: '',
          img: '',
          isRight: false
        }
      ], // 存储选项
      questionIndex: 4, // 最少4
      questionList: [], // 题库列表
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: ' ', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: ['change', 'blur']
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择目录',
            trigger: ['change', 'blur']
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业',
            trigger: ['change', 'blur']
          }
        ],
        province: [
          {
            required: true,
            message: '请选择地区',
            trigger: ['change', 'blur']
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向',
            trigger: ['change', 'blur']
          }
        ],
        questionType: [
          {
            required: true,
            message: '请选择方向',
            trigger: ['change']
          }
        ],
        difficulty: [
          {
            required: true,
            message: '请选择方向',
            trigger: ['change']
          }
        ],
        question: [
          {
            required: true,
            message: '请输入题干',
            trigger: ['change', 'blur']
          }
        ],
        answer: [
          {
            required: true,
            message: '请输入答案解析',
            trigger: ['change', 'blur']
          }
        ],
        videoURL: [
          {
            required: true,
            message: '请输入解析视频地址',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  watch: {
    '$route.query.id' () {
      location.reload()
      this.getQuestionsInfo()
    }
  },
  created () {
    this.date = Date.now()
    this.getSubjectList()
    this.getCompanyList()
    this.getQuestionsInfo()
  },

  methods: {
    // 获取学科列表
    async getSubjectList () {
      try {
        // console.log(simple())
        const { data } = await subList({ page: 1, pagesize: 100 })
        this.subjects = data.items
      } catch (error) {
        console.log(error)
      }
    },
    // 获取企业列表
    async getCompanyList () {
      const { data } = await company()
      // console.log(data)
      this.companyList = data.items
    },
    // 城市发生变化
    onProvinceChange (val) {
      this.form.city = ''
      this.city = getCitys(val)
    },
    // 学科改变触发
    async subjectChange (val) {
      try {
        this.catalogID = ''
        const { data: dirData } = await dirList({ subjectID: val })
        const { data: tagData } = await tagArr({ subjectID: val })
        this.directoryList = dirData.items
        this.tagList = tagData
      } catch (error) {}
    },
    // 添加选项
    addItem () {
      if (this.questionIndex > 7) {
        return
      }
      this.questionIndex++
    },
    // 获取试题信息
    async getQuestionsInfo () {
      if (this.$route.query.id) {
        const { data } = await queList({ id: this.$route.query.id })
        console.log(data);
        this.form = data
        // 或取得长度就是选项数
        this.questionIndex = this.form.options.length
        this.form.tags = data.tags.split(',')
        const array1 = this.array
        // 对添加按钮的数据进行处理
        const newArr = array1.splice(+this.form.options.length)
        this.array = this.form.options.concat(newArr)
        // 获取目录
        const { data: dirData } = await dirList({
          subjectID: this.form.subjectID
        })
        this.directory = dirData.items
        switch (this.form.questionType) {
          // 单选
          case '1':
            this.form.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.radio = index
              }
            })
            break
          // 多选
          case '2':
            this.form.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.checkList.push(index)
              }
            })
            break
        }
      }
    },
    // 提交
    onClick (e) {
      this.$refs.form.validate(async (isOk) => {
        if (!isOk) {
          return false
        } else {
          if (!this.$route.query.id) {
            this.onSubmit()
            this.$message.success('添加成功')
          } else {
            this.form.tags = this.form.tags.join(',')
            switch (this.form.questionType) {
              // 单选
              case '1':
                // eslint-disable-next-line no-case-declarations
                const optionArr = this.array.slice(0, 4)
                // 判断默认勾选
                optionArr.forEach((item, index) => {
                  if (index === this.radio) {
                    item.isRight = true
                  } else {
                    item.isRight = false
                  }
                })
                this.form.options = optionArr
                break

              // 多选的情况
              case '2':
                // eslint-disable-next-line no-case-declarations
                const arr = this.array.slice(0, this.questionIndex)
                // 判断默认勾选
                for (let i = 0; i < arr.length; i++) {
                  this.checkList.forEach((item) => {
                    if (i === item) {
                      arr[i].isRight = true
                    }
                  })
                }
                this.form.options = arr
                break
            }
            await queUpdate(this.form)
            this.$message.success('修改成功')
          }
          this.$router.push('list')
        }
      })
    },
    async onSubmit () {
      // 标签要是字符串形式
      this.form.tags = this.form.tags.join(',')
      // 单复选
      switch (this.form.questionType) {
        // 单选题
        case '1':
          // eslint-disable-next-line no-case-declarations
          const optionArr = this.array.slice(0, 4)
          // 选项
          optionArr.forEach((item, index) => {
            if (index === this.radio) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
          this.form.options = optionArr
          break

        // 多选的情况
        case '2':
          // eslint-disable-next-line no-case-declarations
          const arr = this.array.slice(0, this.questionIndex)
          // 判断默认勾选
          for (let i = 0; i < arr.length; i++) {
            this.checkList.forEach((item) => {
              if (i === item) {
                arr[i].isRight = true
              }
            })
          }
          this.form.options = arr
          break
      }
      await add(this.form)
    }
  }
}
</script>

<style scoped>
.quill-editor {
  margin-bottom: 60px;
}
.upload_btn {
  margin-top: -10px;
  height: 50px;
}
.addBtn {
  margin: 10px 0px 20px;
  margin-left: 120px;
}
</style>
